﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PMSGSC.Common;
using DevExpress.XtraEditors;
using PMSGSC.DAL;
using PMSGSC.BLL;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraEditors.Controls;
using System.Globalization;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Columns;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Data.Linq;
using DevExpress.Utils.OAuth.Provider;
using DevExpress.XtraRichEdit.Model;
using System.Diagnostics;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraGrid.Localization;
using DevExpress.XtraTab;
using DevExpress.XtraBars;
using DevExpress.XtraRichEdit;
using DevExpress.XtraPrinting;

namespace PMSGSC.App
{
    public partial class frmComponent : DevExpress.XtraEditors.XtraForm
    {
        public frmComponent(List<Equipment> equipmentList, frmMain objMain)
        {
            InitializeComponent();

            equipmentBindingSource.DataSource = equipmentList;
            statusBindingSource.DataSource = Status_BLL.GetAll(frmMain.ship.Ship_ID);
            locationBindingSource.DataSource = Location_BLL.GetAll(frmMain.ship.Ship_ID);
            makerBindingSource.DataSource = Maker_BLL.GetAll(frmMain.ship.Ship_ID);
            vendorBindingSource.DataSource = Vendor_BLL.GetAll(frmMain.ship.Ship_ID);
            main = objMain;
        }
        frmMain main;
        Equipment equip = null;
        private void LoadDataIntoTabPage()
        {
            XtraTabPage tabpage = tabCotrolComponent.SelectedTabPage;
            if (equip != null)
            {
                switch (tabpage.Name)
                {
                    case "Jobs":
                        jobBindingSource.DataSource = Job_BLL.GetDataByEquipmentID(equip.Equipment_ID, frmMain.ship.Ship_ID, false);
                        break;
                    case "Parts":
                        partsInEquipmentBindingSource.DataSource = PartInEquipment_BLL.GetDataByEquipmentID(equip.Equipment_ID, isChangedA);
                        break;
                    case "Attachments":
                        attachmentBindingSource.DataSource = Attachment_BLL.GetDataByEquipmentID(equip.Equipment_ID, isChangedA);
                        isChangedA = false;
                        break;
                    case "WO":
                        workOrderBindingSource.DataSource = WorkOrder_BLL.GetDataByEquipmentID(equip.Equipment_ID, frmMain.ship.Ship_ID, false);
                        break;
                    case "Counter":
                        equipmentBindingSource1.DataSource = Equipment_BLL.GetDataById(equip.Equipment_ID);
                        break;
                    case "History":
                        historyBindingSource.DataSource = History_BLL.GetDataByEquipmentID(equip.Equipment_ID);
                        break;
                }
            }
            else
            {
                switch (tabpage.Name)
                {
                    case "Jobs":
                        jobBindingSource.DataSource = Job_BLL.GetDataByEquipmentID(0, frmMain.ship.Ship_ID, false);
                        break;
                    case "Parts":
                        partsInEquipmentBindingSource.DataSource = null;
                        break;
                    case "Attachments":
                        attachmentBindingSource.DataSource = null;
                        break;
                    case "WO":
                        workOrderBindingSource.DataSource = null;
                        break;
                    case "Counter":
                        equipmentBindingSource1.DataSource = null;
                        break;
                    case "History":
                        historyBindingSource.DataSource = null;
                        break;
                }
            }
        }

        public void SaveComponent()
        {
            SetValueBeforeInsert();
            foreach (Equipment eq in equipmentBindingSource.Cast<Equipment>().ToList())
            {
                bool result = Equipment_BLL.Update(eq);
            }
        }

        private void SetValueBeforeInsert()
        {
            if (nameEquipmentTextEdit.ContainsFocus)
                equip.NameEquipment = nameEquipmentTextEdit.Text;

            if (codeEquipmentMaskedTextBox.ContainsFocus)
                equip.CodeEquipment = codeEquipmentMaskedTextBox.Text;

            if (serialTextEdit.ContainsFocus)
                equip.Serial = serialTextEdit.Text;

            if (ucRichEditControl1.isChange)
            {
                equip.Details = ucRichEditControl1.richEditControl1.Text;
                ucRichEditControl1.isChange = false;
            }

            if (ucLoadMaker1.lb_id.Text != "")
                equip.Maker = BaseDAL.DB.Makers.Single(c => c.Maker_ID == int.Parse(ucLoadMaker1.lb_id.Text));

            if (ucLoadVendor1.lbid.Text != "")
                equip.Vendor = BaseDAL.DB.Vendors.Single(c => c.Vendor_ID == int.Parse(ucLoadVendor1.lbid.Text));
        }

        private void status_IDLookUpEdit_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            if (e.NewValue == null)
                ((Equipment)gridView5.GetFocusedRow()).Status = null;
            else
                ((Equipment)gridView5.GetFocusedRow()).Status = BaseDAL.DB.Status.Single(c => c.Status_ID == (int)e.NewValue);
        }

        private void location_IDGridLookUpEdit_EditValueChanging(object sender, DevExpress.XtraEditors.Controls.ChangingEventArgs e)
        {
            if (e.NewValue == null)
                ((Equipment)gridView5.GetFocusedRow()).Location = null;
            else
                ((Equipment)gridView5.GetFocusedRow()).Location = BaseDAL.DB.Locations.Single(c => c.Location_ID == (int)e.NewValue);
        }

        private bool TestBeforeAddJob()
        {
            if (equip != null)
                return true;
            return false;
        }

        // Lấy Equipment theo ParentID để tạo cây
        private List<Equipment> GetDataByParentID(int ParentID)
        {
            List<Equipment> Temp = new List<Equipment>();
            foreach (Equipment e in equipmentBindingSource.Cast<Equipment>().ToList())
            {
                if (e.ParentID == ParentID)
                {
                    Temp.Add(e);
                }
            }
            return Temp;
        }

        // Nếu thiết bị có con thì đệ quy xuống 
        private void DeleteChildNode(int ParentID)
        {
            List<Equipment> childEquipment = GetDataByParentID(ParentID);
            if (childEquipment.Count > 0)
            {
                foreach (Equipment e in childEquipment)
                {
                    Equipment_BLL.Delete(e);
                    DeleteChildNode(e.Equipment_ID);
                }
            }
        }

        private void DeleteComponent()
        {
            if (Equipment_BLL.TestBeforeDeleteComponentFinal(equip.Equipment_ID))
            {
                equipmentBindingSource.Cast<Equipment>().ToList().Remove(equip);
                Equipment_BLL.Delete(equip);
                DeleteChildNode(equip.Equipment_ID);
                gridControl1.DataSource = equipmentBindingSource.DataSource;
            }
            else
            {
                XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void equipmentBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            if (equip != null)
            {
                if (ucLoadMaker1.isChanges || ucLoadVendor1.isChanges || ucRichEditControl1.isChange)
                {
                    if (ucLoadMaker1.lb_id.Text != "")
                        equip.Maker = BaseDAL.DB.Makers.Single(c => c.Maker_ID == int.Parse(ucLoadMaker1.lb_id.Text));

                    if (ucLoadVendor1.lbid.Text != "")
                        equip.Vendor = BaseDAL.DB.Vendors.Single(c => c.Vendor_ID == int.Parse(ucLoadVendor1.lbid.Text));

                    equip.Details = ucRichEditControl1.richEditControl1.Text;

                    ucLoadMaker1.isChanges = false;
                    ucLoadVendor1.isChanges = false;
                    ucRichEditControl1.isChange = false;
                }
            }

            equip = equipmentBindingSource.Current as Equipment;
            if (equip != null)
            {
                ucRichEditControl1.richEditControl1.Text = equip.Details;

                if(equip.Maker != null)
                    ucLoadMaker1.SetValue(equip.Maker.CodeMaker, equip.Maker.NameMaker, equip.Maker.Maker_ID.ToString());
                else
                    ucLoadMaker1.SetValue("", "", "");

                if(equip.Vendor != null)
                    ucLoadVendor1.SetValue(equip.Vendor.CodeVendor, equip.Vendor.NameVendor, equip.Vendor.Vendor_ID.ToString());
                else
                    ucLoadVendor1.SetValue("", "", "");
            }

            Equipment parrentEquip = Equipment_BLL.GetDataById(equip.ParentID);
            if (parrentEquip != null)
            {
                txtParentCodeComp.Text = parrentEquip.CodeEquipment;
                txtParentNameComp.Text = parrentEquip.NameEquipment;
            }
            else
            {
                txtParentCodeComp.Text = "";
                txtParentNameComp.Text = "";
            }

            LoadDataIntoTabPage();
        }

        #region Attachment

        private byte[] StreamFile(string fileName)
        {
            // Open file
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);

            // ByteArray
            byte[] ImageData = new byte[fs.Length];

            // Read block of bytes
            fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));

            // Close it
            fs.Close();

            // Return the byte data
            return ImageData;
        }
        public bool ByteArrayToFile(string fileName, byte[] byteArray)
        {
            try
            {
                // Open file for reading
                System.IO.FileStream fileStream = new System.IO.FileStream
                    (fileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                // Writes a block of bytes
                fileStream.Write(byteArray, 0, byteArray.Length);

                // Close file stream
                fileStream.Close();

                return true;
            }
            catch (Exception exp)
            {
                Console.WriteLine(exp.ToString());
            }
            return false;
        }
        private bool isChangedA;
        private void attachmentBindingSource_CurrentItemChanged(object sender, EventArgs e)
        {
            isChangedA = true;
        }
        private void repositoryItemButtonEdit2_ButtonClick(object sender, ButtonPressedEventArgs e)
        {
            try
            {
                OpenDocument();
            }
            catch { }
        }
        private void btnUploadFile_ButtonClick(object sender, ButtonPressedEventArgs e)
        {

            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "Select one file upload";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {

                string fileName = openFileDialog.InitialDirectory + openFileDialog.FileName;
                FileInfo fileInfo = new FileInfo(fileName);
                long sizeFile = fileInfo.Length / 1000;
                if (sizeFile <= 3000)
                {
                    string extension = Path.GetExtension(fileName);
                    attachment.Extension = extension;
                    byte[] fileByteArray = StreamFile(fileName);
                    // Converts it to Binary
                    // it can be done inside the method as well
                    Binary fileBinary = new Binary(fileByteArray);
                    attachment.ContentFile = fileBinary;
                    GridColumn AttachExtension = gridView18.Columns["Extension"];
                    extension = extension.ToUpper();
                    gridView18.SetRowCellValue(gridView18.FocusedRowHandle, AttachExtension, extension);
                }
                else
                {
                    XtraMessageBox.Show("The size file  must be less than 3M ", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }

            }

        }
        // Khai báo trạng thái mặc định 
        private Status statusAttachment = Status.Update;
        // Tạo một đối tượng lưu trữ các thông tin trên View ==> truyền xuống các layer bên dưới
        private Attachment attachment = new Attachment();
        //Hiển thị số thứ tự của gridview
        private void gridViewA_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
        // Sự kiện cập nhật dữ liệu xuống database
        LockMouseClickEvent lockMouseClick = new LockMouseClickEvent();
        private void gridViewA_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            SaveAttachmentToDatabase();
        }
        private void SaveAttachmentToDatabase()
        {
            if (TestBeforeAddJob())
            {
                frmProcessBar pb = new frmProcessBar();
                System.Threading.Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
                {
                    LoadSkinToForm();
                    pb.ShowDialog();
                }
                ));
                if (statusAttachment == Status.Update)
                {
                    thread.Start();
                    bool result = Attachment_BLL.Update(attachment);
                    if (!result)
                        XtraMessageBox.Show("Update Unsuccess !", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    else
                        XtraMessageBox.Show("Update Success !", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);


                    attachmentBindingSource.DataSource = Attachment_BLL.GetDataByEquipmentID(equip.Equipment_ID, isChangedA);
                    isChangedA = false;
                }

                if (statusAttachment == Status.New)
                {
                    thread.Start();
                    attachment.Equipment_ID = equip.Equipment_ID;
                    bool result = Attachment_BLL.Insert(attachment);
                    if (!result)
                    {
                        XtraMessageBox.Show("Insert Unsuccess!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    statusAttachment = Status.Update;
                }

                if (pb.InvokeRequired)
                    pb.BeginInvoke(new Action(() => pb.Close()));
            }
        }
        private static void LoadSkinToForm()
        {
            DevExpress.Skins.SkinManager.EnableFormSkins();
            DevExpress.UserSkins.BonusSkins.Register();
            DevExpress.UserSkins.OfficeSkins.Register();
            DevExpress.LookAndFeel.DefaultLookAndFeel obj = new DevExpress.LookAndFeel.DefaultLookAndFeel();
            try
            {
                LookAndFeelSettings.Load("LookAndFeelSettings.dat");
            }
            catch
            {
                obj.LookAndFeel.SetSkinStyle("Blue");
            }
        }
        
        private void DeleteAttachment(NavigatorButtonClickEventArgs e)
        {
            DeleteAttachmentFinal();
            e.Handled = true;
        }

        private void DeleteAttachmentFinal()
        {
            if (XtraMessageBox.Show("Are you sure you want to delete a Attachment?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                attachment = attachmentBindingSource.Current as Attachment;
                bool result = Attachment_BLL.Delete(attachment);
                if (!result)
                {
                    XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                attachmentBindingSource.DataSource = Attachment_BLL.GetDataByEquipmentID(equip.Equipment_ID, isChangedA);
                isChangedA = false;
            }
        }
        // Sự kiện nhân phím delete sảy ra
        private void gridViewA_KeyDown(object sender, KeyEventArgs e)
        {
            if (TestBeforeAddJob())
            {
                if (e.KeyCode == Keys.Delete)
                {
                    DeleteAttachmentFinal();
                }
            }
        }
        // Khởi tạo giá trị mặc định của ô cần ràng buộc
        private void gridViewA_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            if (TestBeforeAddJob())
            {
                statusAttachment = Status.New;
            }
        }
        // Kiểm tra ràng buộc của dữ liệu người dùng nhập vào
        private void gridViewA_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            if (equip != null)
            {
                GridView view = (GridView)sender;
                GridColumn AttachName = view.Columns["Name"];
                GridColumn AttachCode = view.Columns["Code"];
                GridColumn AttachContent = view.Columns["ContentFile"];

                if (null == view.GetRowCellValue(e.RowHandle, AttachName))
                {
                    e.Valid = false;
                    view.FocusedColumn = AttachName;
                    e.ErrorText = "Please enter the Attachment Name. ";
                    view.SetColumnError(AttachName, "Attachment Name is not empty");
                    return;
                }
                if (null == view.GetRowCellValue(e.RowHandle, AttachCode))
                {
                    e.Valid = false;
                    view.FocusedColumn = AttachCode;
                    e.ErrorText = "Please enter the Attachment Code. ";
                    view.SetColumnError(AttachCode, "Attachment Code is not empty");
                    return;
                }
                if (null == view.GetRowCellValue(e.RowHandle, AttachContent))
                {
                    e.Valid = false;
                    e.ErrorText = "Please upload one file into table ";
                    return;
                }
                attachment = attachmentBindingSource.Current as Attachment;
                attachment.Equipment_ID = equip.Equipment_ID;
                if (Attachment_BLL.IsExits(attachment))
                {
                    e.Valid = false;
                    view.FocusedColumn = AttachCode;
                    e.ErrorText = "Attachment Code is exits. ";
                    view.SetColumnError(AttachCode, "Attachment Code is exits");
                    return;
                }
            }
        }
        private void attachmentBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            attachment = attachmentBindingSource.Current as Attachment;
        }
        // Thông báo lỗi nếu dữ liệu nhập vào không đúng
        private void gridViewA_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {

            if (e.RowHandle == GridControl.NewItemRowHandle)
            {
                e.WindowCaption = "Input Error";
            }
            else
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
                DialogResult dr = XtraMessageBox.Show(gridControl1.LookAndFeel, this, e.ErrorText + GridLocalizer.Active.GetLocalizedString(GridStringId.ColumnViewExceptionMessage), e.WindowCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                if (dr == DialogResult.No)
                {
                    e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
                    attachmentBindingSource.DataSource = Attachment_BLL.GetDataByEquipmentID(equip.Equipment_ID, isChangedA);
                    isChangedA = false;
                }
            }
        }
        // Đặt lại trạng thái update 
        private void gridViewA_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.RowHandle != GridControl.NewItemRowHandle)
            {
                statusAttachment = Status.Update;
            }
        }
        private void OpenDocument()
        {
            if (gridView18.FocusedRowHandle != GridControl.NewItemRowHandle)
            {
                string Address = Application.StartupPath + "\\Attachment\\";
                Directory.CreateDirectory(Address);
                attachment = attachmentBindingSource.Current as Attachment;
                Attachment attach = Attachment_BLL.GetDataById(attachment.Attachments);

                if (null != attach)
                {
                    string fileName = attach.Name + attach.Extension;
                    Address += fileName;
                    if (ByteArrayToFile(Address, attach.ContentFile.ToArray()))
                    {
                        try
                        {
                            Process.Start(Address);
                        }
                        catch
                        {

                        }
                    }
                }
            }
        }

        #endregion

        #region Update Counter

        // Tạo một đối tượng lưu trữ các thông tin trên View ==> truyền xuống các layer bên dưới
        private Equipment equipment = new Equipment();
        //Hiển thị số thứ tự của gridview
        private void gridViewC_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
        // Sự kiện cập nhật dữ liệu xuống databse
        private void gridViewC_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            SaveCounterToDatabase();
        }
        private void SaveCounterToDatabase()
        {
            if (XtraMessageBox.Show("Do you want to save changes", "Infomation", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {
                equipment = equipmentBindingSource.Current as Equipment;

                HistoryCounter counterHistory = new HistoryCounter();
                counterHistory.Counters = equipment.CurrentCounter;
                counterHistory.DateUpdate = equipment.TempDate;
                counterHistory.Equipment_ID = equipment.Equipment_ID;
                bool historyResult = CounterHistory_BLL.Insert(counterHistory);

                int ValueChange = equipment.CurrentCounter.Value - equipment.OldCounter.Value;
                WorkOrder_BLL.UpdateCounterOfJob(equipment.Equipment_ID, ValueChange);

                equipment.OldCounter = equipment.CurrentCounter;
                equipment.IsCounter = true;

                bool result = Equipment_BLL.UpdateCounter(equipment);
                XtraMessageBox.Show("Save success !", "Infomation", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        // Sự kiện click vào thành Navigator
        private void datnaviMainC_ButtonClick(object sender, DevExpress.XtraEditors.NavigatorButtonClickEventArgs e)
        {
            switch (e.Button.ButtonType)
            {
                case NavigatorButtonType.EndEdit:
                    SaveCounterToDatabase();
                    break;
            }
        }
        private void txtSetvalue_KeyPress(object sender, KeyPressEventArgs e)
        {
            OnlyInputNumberic(e);
        }

        #endregion

        #region History

        private void gridViewH_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        #endregion

        #region Part

        // Khai báo trạng thái mặc định 
        private Status statusPart = Status.Update;
        // Tạo một đối tượng lưu trữ các thông tin trên View ==> truyền xuống các layer bên dưới
        private PartsInEquipment part = new PartsInEquipment();
        private bool isChanged;
        //Hiển thị số thứ tự của gridview
        private void gridViewP_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
        // Sự kiện cập nhật dữ liệu xuống database
        private void gridViewP_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            SavePartEToDatabase();
        }

        private void partsInEquipmentBindingSource_CurrentChanged(object sender, EventArgs e)
        {
            part = partsInEquipmentBindingSource.Current as PartsInEquipment;
        }

        private void partsInEquipmentBindingSource_CurrentItemChanged(object sender, EventArgs e)
        {
            isChangedA = true;
        }

        private void SavePartEToDatabase()
        {
            if (TestBeforeAddJob())
            {
                part = partsInEquipmentBindingSource.Current as PartsInEquipment;
                part.IsCheck = false;
                if (statusPart == Status.Update)
                {
                    bool result = PartInEquipment_BLL.Update(part);
                    if (!result)
                        XtraMessageBox.Show("Update Unsuccess !", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    else
                        XtraMessageBox.Show("Update Success !", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);


                    partsInEquipmentBindingSource.DataSource = PartInEquipment_BLL.GetDataByEquipmentID(equip.Equipment_ID, isChangedA);
                    isChangedA = false;
                }
                if (statusPart == Status.New)
                {
                    bool result = PartInEquipment_BLL.Insert(part);
                    if (!result)
                    {
                        XtraMessageBox.Show("Insert Unsuccess!", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    statusPart = Status.Update;
                }
            }
        }

        private void DeletePart(NavigatorButtonClickEventArgs e)
        {
            DeletePartFinal();
            e.Handled = true;
        }

        private void DeletePartFinal()
        {
            if (XtraMessageBox.Show("Are you sure you want to delete a Part?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
            {
                part = partsInEquipmentBindingSource.Current as PartsInEquipment;

                if (!PartInEquipment_BLL.TestBeforeDelete(part))
                    PartInEquipment_BLL.Delete(part);
                else
                    XtraMessageBox.Show("Can't Delete", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                partsInEquipmentBindingSource.DataSource = PartInEquipment_BLL.GetDataByEquipmentID(equip.Equipment_ID, isChangedA);
                isChangedA = false;
            }
        }
        // Sự kiện nhân phím delete sảy ra
        private void gridViewP_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                DeletePartFinal();
            }
        }
        // Khởi tạo giá trị mặc định của ô cần ràng buộc
        private void gridViewP_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            if (TestBeforeAddJob())
            {
                statusPart = Status.New;
            }
        }
        // Kiểm tra ràng buộc của dữ liệu người dùng nhập vào
        private void gridViewP_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            if (equip != null)
            {
                GridView view = (GridView)sender;
                GridColumn PartCode = view.Columns[1];
                GridColumn PartName = view.Columns[2];
                if (null == view.GetRowCellValue(e.RowHandle, PartCode))
                {
                    e.Valid = false;
                    view.FocusedColumn = PartCode;
                    e.ErrorText = "Please enter the Part";
                    view.SetColumnError(PartCode, "Part is not empty");
                    view.SetColumnError(PartName, "Part is not empty");
                    return;
                }

                part = partsInEquipmentBindingSource.Current as PartsInEquipment;
                part.Equipment_ID = equip.Equipment_ID;

                if (PartInEquipment_BLL.isExits(part))
                {
                    e.Valid = false;
                    view.FocusedColumn = PartCode;
                    e.ErrorText = "Part is exits. ";
                    view.SetColumnError(PartCode, "Part is exits");
                    view.SetColumnError(PartName, "Part is exits");
                    return;

                }
            }
        }
        // Thông báo lỗi nếu dữ liệu nhập vào không đúng
        private void gridViewP_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            if (e.RowHandle == GridControl.NewItemRowHandle)
            {
                e.WindowCaption = "Input Error";
            }
            else
            {
                e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
                DialogResult dr = XtraMessageBox.Show(gridControl1.LookAndFeel, this, e.ErrorText + GridLocalizer.Active.GetLocalizedString(GridStringId.ColumnViewExceptionMessage), e.WindowCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Error);
                if (dr == DialogResult.No)
                {
                    e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.Ignore;
                    partsInEquipmentBindingSource.DataSource = PartInEquipment_BLL.GetDataByEquipmentID(equip.Equipment_ID, isChangedA);
                    isChangedA = false;
                }
            }
        }
        // Đặt lại trạng thái update 
        private void gridViewP_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.RowHandle != GridControl.NewItemRowHandle)
            {
                statusPart = Status.Update;
            }
        }
        private static void OnlyInputNumberic(KeyPressEventArgs e)
        {
            const char Delete = (char)8;
            e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
        }

        #endregion

        private void equipmentBindingSource_CurrentItemChanged(object sender, EventArgs e)
        {
            isChanged = true;
        }

        private void tabCotrolComponent_SelectedPageChanged(object sender, TabPageChangedEventArgs e)
        {
            LoadDataIntoTabPage();
        }
        private void btnNewJob_Click(object sender, EventArgs e)
        {
            if (equip != null)
            {
                frmNewJob newJob = new frmNewJob(equip.Equipment_ID, 0);
                newJob.ShowDialog();
                jobBindingSource.DataSource = Job_BLL.GetDataByEquipmentID(equip.Equipment_ID, frmMain.ship.Ship_ID, true);
            }
        }

        private void gridView12_ShowingEditor(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }

        private void gridView12_DoubleClick(object sender, EventArgs e)
        {
            GridView view = (GridView)sender;

            Point pt = view.GridControl.PointToClient(Control.MousePosition);

            DoRowDoubleClick(view, pt);
        }

        private void DoRowDoubleClick(GridView view, Point pt)
        {
            GridHitInfo info = view.CalcHitInfo(pt);

            if (info.InRow || info.InRowCell)
            {
                if (info.RowHandle != GridControl.NewItemRowHandle)
                {
                    Job objJob = jobBindingSource.Current as Job;

                    frmNewJob newJob = new frmNewJob(objJob.Equipment_ID.Value, objJob.Job_ID);
                    newJob.ShowDialog();
                    jobBindingSource.DataSource = Job_BLL.GetDataByEquipmentID(equip.Equipment_ID, frmMain.ship.Ship_ID, true);
                }

            }

        }

        private void btnDeleteJob_Click(object sender, EventArgs e)
        {
            Job j = jobBindingSource.Current as Job;
            if (j != null)
            {
                if (!Job_BLL.TestBeforeDelete(j))
                {
                    XtraMessageBox.Show("Can't Delete", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                   bool result = Job_BLL.Delete(j);
                }
                jobBindingSource.DataSource = Job_BLL.GetDataByEquipmentID(equip.Equipment_ID, frmMain.ship.Ship_ID, true);
            }
        }

        private void codeEquipmentMaskedTextBox_Validating(object sender, CancelEventArgs e)
        {
            if (equip != null)
            {
                Equipment eq = new Equipment();
                eq.CodeEquipment = codeEquipmentMaskedTextBox.Text;
                eq.Equipment_ID = equip.Equipment_ID;
                if (Equipment_BLL.IsExits(eq))
                {
                    XtraMessageBox.Show("Number Code has exitsed in table", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    e.Cancel = true;
                    return;
                }
            }
        }

        private void gridView5_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void gridView5_ShowingEditor(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }

        private void gridView12_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void dataNavigator1_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            switch (e.Button.ButtonType)
            {
                case NavigatorButtonType.CancelEdit:
                    DeleteComponent();
                    equipmentBindingSource.DataSource = Equipment_BLL.GetAll(frmMain.ship.Ship_ID);
                    break;
            }
        }

        private void frmComponent_SizeChanged(object sender, EventArgs e)
        {
           // panelControl1.Height = this.Height - 30;
        }

        private void btnSaveAll_ItemClick(object sender, ItemClickEventArgs e)
        {
            SaveComponent();
            XtraMessageBox.Show("Save Successly!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void btnDelete_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraMessageBox.Show("Function building", "Information", MessageBoxButtons.OK, MessageBoxIcon.Warning);
           // DeleteComponent(); 
        }

        private void btnRefresh_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraMessageBox.Show("Function building", "Information", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            //equipmentBindingSource.DataSource = Equipment_BLL.GetAll(frmMain.ship.Ship_ID);
        }

        private void btnPrint_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraMessageBox.Show("Function building", "Information", MessageBoxButtons.OK, MessageBoxIcon.Warning);
           // PrintDocument();
        }
       
        private void printToolStripMenuItem_Click(object sender, EventArgs e)
        {
           // PrintDocument();
        }

        private void gridControl1_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            switch (e.Button.ButtonType)
            {
                case NavigatorButtonType.CancelEdit:
                    DeleteComponent();
                    equipmentBindingSource.DataSource = Equipment_BLL.GetAll(frmMain.ship.Ship_ID);
                    break;
            }
        }

        private void gridControl4_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            if (TestBeforeAddJob())
            {
                switch (e.Button.ButtonType)
                {
                    case NavigatorButtonType.Remove:
                        if (TestBeforeAddJob())
                        {
                            DeletePart(e);
                        }
                        break;
                }
            }
        }

        private void gridControl12_EmbeddedNavigator_ButtonClick(object sender, NavigatorButtonClickEventArgs e)
        {
            if (TestBeforeAddJob())
            {
                switch (e.Button.ButtonType)
                {
                    case NavigatorButtonType.Remove:
                        if (TestBeforeAddJob())
                        {
                            DeleteAttachment(e);
                        }
                        break;
                }
            }
        }

        private void gridView24_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void gridView18_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void gridView24_ShowingEditor(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }

        private void gridView29_ShowingEditor(object sender, CancelEventArgs e)
        {
            e.Cancel = true;
        }

        private void btnNewComponent_ItemClick(object sender, ItemClickEventArgs e)
        {
            XtraMessageBox.Show("Function building", "Information", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        private void gluMaker_EditValueChanging(object sender, ChangingEventArgs e)
        {
            if (e.NewValue == null)
                ((PartsInEquipment)gridView16.GetFocusedRow()).Maker = null;
            else
                ((PartsInEquipment)gridView16.GetFocusedRow()).Maker = BaseDAL.DB.Makers.Single(c => c.Maker_ID == (int)e.NewValue);
        }

        private void gluVendor_EditValueChanging(object sender, ChangingEventArgs e)
        {
            if (e.NewValue == null)
                ((PartsInEquipment)gridView16.GetFocusedRow()).Vendor = null;
            else
                ((PartsInEquipment)gridView16.GetFocusedRow()).Vendor = BaseDAL.DB.Vendors.Single(c => c.Vendor_ID == (int)e.NewValue);
        }

        private void gridView29_DoubleClick(object sender, EventArgs e)
        {
            GridView view = (GridView)sender;

            Point pt = view.GridControl.PointToClient(Control.MousePosition);

            DoRowDoubleClickHistory(view, pt);
        }

        private void DoRowDoubleClickHistory(GridView view, Point pt)
        {
            GridHitInfo info = view.CalcHitInfo(pt);

            if (info.InRow || info.InRowCell)
            {
                if (info.RowHandle != GridControl.NewItemRowHandle)
                {
                    List<History> histories = History_BLL.GetAllByEquipment(equip.Equipment_ID);
                    frmHistoryDetail historyDetail = new frmHistoryDetail(histories);
                    historyDetail.MdiParent = main;
                    historyDetail.Show();
                }
            }
        }

        private void gridView17_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column == colCurrentCounter)
            {
                GridView view = sender as GridView;
                GridColumn dateCol = view.Columns[4];
                view.SetFocusedRowCellValue(dateCol, DateTime.Today.ToString());
            }
        }

        private void gridView17_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }
    }
}